# File: Gentoo ebuild generator for R langiage modules

import fileinput
import os

L = list()
for line in fileinput.input("PACKAGES"):
    if line != '\n':
				
        array = line.rstrip('\n').replace(' ','').split(':')
        line.rstrip('\w').rstrip(' ').rstrip(' ').rstrip('\t')
        if len( array) == 2:
            L.append(array)
        else:
            L[-1][1] += array[0]
    else:
        for items in L:
            if items[0] == 'Package':
                package = items[1]
            elif items[0] == 'Version':
                version = items[1]
            elif items[0] == 'Depends':
                depends = items[1].split(',')
            elif items[0] == 'Imports':
                imports = items[1].split(',')
            elif items[0] == 'License':
                license = items[1]
        ebuild_name = package+'-'+version.replace('-','.')
        filename = package+'_'+version+'.tar.gz'
        dir = 'tmp/'+package
        print  ebuild_name
        if not os.path.exists(dir):
            os.makedirs(dir)
        f = open(dir+'/'+ebuild_name+'.ebuild', 'w')
        if package:
            f.write('# Copyright 1999-2009 Gentoo Foundation'+'\n')
            f.write('# Distributed under the terms of the GNU General Public License v2'+'\n')
            f.write('# $Header: '+'\n')
            f.write(''+'\n')
            f.write('MY_P=${PN}-${PV/_}'+'\n')
            f.write('DESCRIPTION="R system package"'+package+'\n')
            f.write('HOMEPAGE="http://r-forge.r-project.org/"'+'\n')
            f.write('SRC_URI="http://cran.r-project.org/src/contrib/'+filename+'"'+'\n')
            f.write(''+'\n')
            f.write('LICENSE="GPL-2"'+'\n')
            f.write('SLOT="0"'+'\n')
            f.write('KEYWORDS="alpha amd64 arm hppa ia64 m68k ~mips ppc ppc64 s390 sh sparc ~sparc-fbsd x86 ~x86-fbsd"'+'\n')
            f.write('IUSE=""'+'\n')
            f.write('DEPEND=">=dev-lang/R-2.0.0"'+'\n')
            f.write(''+'\n')
            f.write('src_install() {'+'\n')
            f.write('\t'+'/usr/bin/R CMD INSTALL -l ${WORKDIR} /usr/portage/distfiles/'+filename+'\n')
            f.write('\t'+'insinto /usr/lib/R/library'+'\n')
            f.write('\t'+'cp -R "${WORKDIR}/'+package+'" "${D}usr/lib/R/library/" || die "Install failed!"'+'\n')
            f.write('}'+'\n')
        L = list()
